package java8.stream.demo06findstream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

/**
 * @author ChangLiang
 * @date 2020/4/22
 */
public class AppTest {

    Stream<Integer> stream;

    @BeforeEach
    public void setUp(){
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
    }

    @Test
    @DisplayName("test stream find")
    public void test(){
        Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(optional.orElse(-1));
    }

    @Test
    @DisplayName("test stream find")
    public void test2() {
        stream = Arrays.stream(new Integer[]{});
        Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(optional.orElse(-1));
    }

    @Test
    @DisplayName("test stream find")
    public void test3() {
        stream = null;
        Optional<Integer> optional = Optional.ofNullable(stream).orElse(Arrays.stream(new Integer[]{})).filter(i -> i % 2 == 0).findAny();
        System.out.println(optional.orElse(-1));
    }

    @Test
    @DisplayName("test stream find first")
    public void test4() {
        Optional<Integer> optional = Optional.ofNullable(stream).orElse(Arrays.stream(new Integer[]{})).filter(i -> i % 2 == 0).findFirst();
        System.out.println(optional.orElse(-1));
    }

    @Test
    @DisplayName("test stream find")
    public void test5() {
        int result = find(new Integer[]{1, 2, 3, 4, 5, 6, 7}, -1, i -> i > 8);
        assertThat(result).isEqualTo(-1);
    }

    private static int find(Integer[] values, int defaultValue, Predicate<Integer> predicate) {
        for (int i : values) {
            if (predicate.test(i)) {
                return i;
            }
        }
        return defaultValue;
    }
}
